package com.mallcloud.mall.mall.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mallcloud.mall.app.config.BaseConfig;
import com.mallcloud.mall.common.core.constant.CacheConstants;
import com.mallcloud.mall.common.core.constant.enums.mall.MallCommonEnum;
import com.mallcloud.mall.mall.api.entity.MallAdvertisingModel;
import com.mallcloud.mall.mall.mapper.MallAdvertisingMapper;
import com.mallcloud.mall.mall.service.MallAdvertisingService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@AllArgsConstructor
public class MallAdvertisingServiceImpl extends ServiceImpl<MallAdvertisingMapper, MallAdvertisingModel> implements MallAdvertisingService {
	private final BaseConfig baseConfig;

	@Override
	@Cacheable(value = CacheConstants.ADVERTISING, key = "#dto.advertisingTypeId", unless = "#result.isEmpty()")
	public List<MallAdvertisingModel> listAdvertising(MallAdvertisingModel dto) {
		List<MallAdvertisingModel> resList = this.list(Wrappers.lambdaQuery(dto)
				.lt(MallAdvertisingModel::getActivityTime, new Date())
				.orderByDesc(MallAdvertisingModel::getCreateTime)
		);

		resList.forEach(x -> {
			if(StrUtil.isNotBlank(x.getPathImage())){
				// 替换成nginx静态资源地址
				x.setPathImage(String.format("%s%s", baseConfig.getNginxUrl(), StrUtil.subAfter(x.getPathImage(), StrUtil.SLASH, true)));
			}
		});
		return resList;
	}

	@Override
	@CacheEvict(value = CacheConstants.ADVERTISING, key = "#dto.advertisingType")
	public Boolean saveAdvertising(MallAdvertisingModel dto) {
		return this.save(dto);
	}

	@Override
	@CacheEvict(value = CacheConstants.ADVERTISING, key = "#dto.advertisingType")
	public Boolean updateAdvertising(MallAdvertisingModel dto) {
		return this.updateById(dto);
	}

	@Override
	@CacheEvict(value = CacheConstants.ADVERTISING, allEntries = true)
	public Boolean removeAdvertisingByIds(List<Long> ids) {
		return this.removeBatchByIds(ids);
	}

	@Override
	@CacheEvict(value = CacheConstants.ADVERTISING, allEntries = true)
	public void clearAll(){ }

}
